package cn.huaemei.test;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author Roden
 */
public class HuaemeiDploy {
    public static Logger log = LoggerFactory.getLogger(HuaemeiDploy.class);
    // 表示程序执行成功
    public static final int SUCCESS = 0;
    private static final int  BUFFER_SIZE = 2 * 1024;

    public static final String HUAEMEI_1_KEY="D:/project/huaemei/config/huaemei_ssh_login";
    public static final String HUAEMEI_2_KEY="D:/project/huaemei/config/huaemei_ssh_login";

    public static final String HUAEMEI_BASE_PATH="D:/project/huaemei/hym";
    public static final String ADMIN_VUE_BASE_PATH="D:/project/huaemei/hyj-admin-vue";
    public static final String ADMIN_API_BASE_PATH="D:/project/huaemei/hyj-admin";

    @Test
    public void test() throws Exception {

    }

    @Test
    public void huaemei() throws Exception {
        File file=new File(HUAEMEI_BASE_PATH+"/src");
        String pack=HUAEMEI_BASE_PATH+"/src.zip";
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pack));
        compress(file ,zos,"",true);
        zos.close();

        scpUpoladHuaemei(getRemote("106.55.51.151",18122,HUAEMEI_1_KEY),pack);
        scpUpoladHuaemei(getRemote("106.52.133.232",18122,HUAEMEI_2_KEY),pack);
    }
    /****************************测试环境************************************************/
    @Test
    public void adminVue_test() throws Exception {
        //1 打包
        String command="cmd.exe /c npm --prefix  "+ADMIN_VUE_BASE_PATH+" run build --qa";
        int exitCode = execCommand(command);
        if (exitCode == SUCCESS) {
            //2 压缩
            File file=new File(ADMIN_VUE_BASE_PATH+"/dist");
            String pack=ADMIN_VUE_BASE_PATH+"/dist.zip";
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pack));
            compress(file ,zos,"",true);
            zos.close();
            //3 上传
            scpUpoladVue(getRemote("106.53.88.25","lxyG5qfqsgct1S"),pack);
        } else {
            System.err.println("exec command error:" + exitCode);
        }
    }

    @Test
    public void adminApi_test() throws Exception {
        File yml = new File(ADMIN_API_BASE_PATH+"/src/main/resources/application.yml");
        YamlUtils.setYmlFile(yml);
        YamlUtils.saveOrUpdateByKey("spring.profiles.active", "test");
        String command="cmd.exe /c mvn -f  "+ADMIN_API_BASE_PATH+"/pom.xml clean package";
        int exitCode = execCommand(command);
        if (exitCode == SUCCESS) {
            String pack=ADMIN_API_BASE_PATH+"/target/admin.jar";
            scpUpoladApi(getRemote("106.53.88.25","lxyG5qfqsgct1S"),pack);
            YamlUtils.saveOrUpdateByKey("spring.profiles.active", "dev");
        } else {
            System.err.println("exec command error:" + exitCode);
        }
    }





     /**************************** 生产环境************************************************/
    @Test
    public void adminVue_prod() throws Exception {
        //1 打包
        String command="cmd.exe /c npm --prefix  "+ADMIN_VUE_BASE_PATH+" run build --prod";

        int exitCode = execCommand(command);
        if (exitCode == SUCCESS) {
            //2 压缩
            File file=new File(ADMIN_VUE_BASE_PATH+"/dist");
            String pack=ADMIN_VUE_BASE_PATH+"/dist.zip";
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(pack));
            compress(file ,zos,"",true);
            zos.close();
            //3 上传
            scpUpoladVue(getRemote("106.55.51.151",18122,HUAEMEI_1_KEY),pack);
            scpUpoladVue(getRemote("106.52.133.232",18122,HUAEMEI_2_KEY),pack);
        } else {
            System.err.println("exec command error:" + exitCode);
        }
    }

    @Test
    public void adminApi_prod() throws Exception {
        File yml = new File(ADMIN_API_BASE_PATH+"/src/main/resources/application.yml");
        YamlUtils.setYmlFile(yml);
        YamlUtils.saveOrUpdateByKey("spring.profiles.active", "prod");
        String command="cmd.exe /c mvn -f  "+ADMIN_API_BASE_PATH+"/pom.xml clean package";
        int exitCode = execCommand(command);
        if (exitCode == SUCCESS) {
            String pack=ADMIN_API_BASE_PATH+"/target/admin.jar";
            scpUpoladApi(getRemote("106.55.51.151",18122,HUAEMEI_1_KEY),pack);
            Thread.sleep(1000*20);
            scpUpoladApi(getRemote("106.52.133.232",18122,HUAEMEI_2_KEY),pack);
            YamlUtils.saveOrUpdateByKey("spring.profiles.active", "dev");
        } else {
            System.err.println("exec command error:" + exitCode);
        }
    }

    public void scpUpoladHuaemei(Remote remote,String pack) throws Exception {
        Session session=getSession(remote);
        JschTest.scpTo(pack,session,"/web/huaemei");
        JschTest.remoteExecute(session,"unzip -o /web/huaemei/src.zip -d /web/huaemei");
        session.disconnect();
    }

    public void scpUpoladVue(Remote remote,String pack) throws Exception {
        Session session=getSession(remote);
        JschTest.remoteExecute(session,"pwd");
        JschTest.scpTo(pack,session,"/web/admin-vue");
        JschTest.remoteExecute(session,"unzip -o /web/admin-vue/dist.zip -d /usr/local/adminvue/dist");
        session.disconnect();
    }

    public void scpUpoladApi(Remote remote,String pack) throws Exception {
        Session session=getSession(remote);
        JschTest.scpTo(pack,session,"/web/admin-api/WEB-INF/lib");
        JschTest.remoteExecute(session,"sh /web/wagou.sh");
        session.disconnect();
    }

    private Remote getRemote(String host , int port,String identity){
        Remote remote = new Remote();
        remote.setHost(host);
        remote.setPort(port);
        remote.setIdentity(identity);
        return remote;
    }

    private Remote getRemote(String host ,String password){
        Remote remote = new Remote();
        remote.setHost(host);
        remote.setPassword(password);
        return remote;
    }

    private Session getSession(Remote remote) throws JSchException {
        Session session = JschTest.getSession(remote);
        session.connect(JschTest.CONNECT_TIMEOUT);
        if (session.isConnected()) {
            log.info("Host({}) connected.",remote.getHost());
        }
        return session;
    }

    private int execCommand(String command) throws Exception {
        // 执行程序
        Runtime runtime = Runtime.getRuntime();
        Process process =runtime.exec(command);
        // 打印程序输出
        readProcessOutput(process);
        // 等待程序执行结束并输出状态
        int exitCode = process.waitFor();
        return exitCode;
    }

    /**
     * 递归压缩方法
     * @param sourceFile 源文件
     * @param zos        zip输出流
     * @param name       压缩后的名称
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     *                          false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */

    private void compress(File sourceFile, ZipOutputStream zos, String name,boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if(KeepDirStructure){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }
            }else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        if(name.equals("")){
                            compress(file, zos, file.getName(),KeepDirStructure);
                        }else {
                            compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                        }

                    } else {
                        compress(file, zos, file.getName(),KeepDirStructure);
                    }
                }
            }
        }
    }

    /**
     * 打印进程输出
     *
     * @param process 进程
     */
    private void readProcessOutput(final Process process) {
        // 将进程的正常输出在 System.out 中打印，进程的错误输出在 System.err 中打印
        read(process.getInputStream(), System.out);
        read(process.getErrorStream(), System.err);
    }

    /**
     * 读取输入流
     * @param inputStream
     * @param out
     */
    private void read(InputStream inputStream, PrintStream out) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
            String line;
            while ((line = reader.readLine()) != null) {
                out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
